package weixin

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

type WeiXin struct {

}
func NewWeiXin () *WeiXin{
	return &WeiXin{}
}
type Result struct {
	Errcode int `json:"errcode"`
	Errmsg string `json:"errmsg"`
	msgId int `json:"msgid"`
}
func (wx WeiXin)SendWxCommonMsg(url string,data []byte) (msgId string,err error) {
	client := http.Client{
		Timeout: time.Second * 3,
	}
	headers := map[string]string{
		"Content-Type": "application/json; charset=utf-8",
		"Accept":"application/json",
	}
	req,err := http.NewRequest("POST",url,strings.NewReader(string(data)))
	if err != nil {
		return
	}
	for key, header := range headers {
		req.Header.Set(key, header)
	}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	var result Result
	err = json.Unmarshal(body,&result)
	if err != nil {
		return
	}
	if result.Errcode == 0{
		msgId = string(result.msgId)
		return
	}
	err = fmt.Errorf("%d,%s",result.Errcode,result.Errmsg)
	return
}
